package cn.com.note.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库操作
 * Created by sunfulin on 2019/1/14.
 */

public class DateUtils {


    /**
     * 获得数据库路径，如果不存在，则创建对象对象
     * @param    name
     */
    public static File getDatabasePath(String name) {
        //判断是否存在sd卡
        boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
        if(!sdExist){//如果不存在,
            Log.e("SD卡管理：", "SD卡不存在，请加载SD卡");
            return null;
        }
        else{//如果存在
            //获取sd卡路径
            String dbDir=android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
            dbDir += "";//数据库所在目录
            String dbPath = dbDir+"/"+name;//数据库路径
            //判断目录是否存在，不存在则创建该目录
            File dirFile = new File(dbDir);
            if(!dirFile.exists())
                dirFile.mkdirs();

            //数据库文件是否创建成功
            boolean isFileCreateSuccess = false;
            //判断文件是否存在，不存在则创建该文件
            File dbFile = new File(dbPath);
            if(!dbFile.exists()){
                try {
                    isFileCreateSuccess = dbFile.createNewFile();//创建文件
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else{
                isFileCreateSuccess = true;
            }


            //返回数据库文件对象
            if(isFileCreateSuccess){
                return dbFile;
            }else{
                return null;
            }
        }
    }



    public static SQLiteDatabase openDatabase(Context context,String path) {
        //SQLiteDatabase.openOrCreateDatabase("/data/data/com.lingdududu.db/databases/stu.db",null);
        //context.getFilesDir().toString()+"/data.db"
        try {
            File file=getDatabasePath("data.db");
            SQLiteDatabase  database = SQLiteDatabase.openOrCreateDatabase(file, null);
            return database;
        } catch (Exception e) {
            Log.i("open error", e.getMessage());
        }
        return null;
    }
    public static String getJson(String fileName,Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
    public static List<String> getData(Context context){


        String json=getJson("json.json",context);

        List<String> list=new ArrayList<>();

        //字符串数组 转为 Json数组
        Gson gson=new Gson();
        List<JSonBean> jsonArray = gson.fromJson(json,new TypeToken<List<JSonBean>>() {
        }.getType());
        for (int i = 0; i < jsonArray.size(); i++) {
            list.add(jsonArray.get(i).getCode());
        }
        return list;
    }

    public static int insertData(SQLiteDatabase db,String tableName, List<String> list){
        int num=0;
        for (int i = 0; i < list.size(); i++) {
            //实例化常量值
            //ContentValues cValue = new ContentValues();
            //添加用户名
            //cValue.put("sname","xiaoming");
            //添加密码
            //cValue.put("snumber","01005");
            //database.insert("data",null,cValue);
            //插入数据SQL语句
            String stu_sql="insert into "+tableName+" (\n" +
                    "DoID,OUTPRO_ZID,OUTPRO_CCNID,\n" +
                    "OUTPRO_NAME,SMF_ZID,SMF_CCNID,\n" +
                    "RMF_ZID,RMF_CCNID,PRO_BARCODE,\n" +
                    "ITEM_COUNT,SCAN_TIME,SCANER_NO,\n" +
                    "OPERATOR_NO,OPERATOR_NAME,F1,VirtualCCNID)\n" +
                    " VALUES(\n" +
                    " '2019014140001','459ffde3ce844cd898e4042eb7b0e8d5e','08971489',\n" +
                    " '君乐宝调制乳(麦香)利乐砖5(...','JXS001','3a16c33632104fd399ac94a00332a1ff',\n" +
                    " 'School0001','a9263b2a7aa14c678aba24660e419db8','"+list.get(i)+"',\n" +
                    " 1,'2019-01-14 14:58:00','869775012981400',\n" +
                    " '3a16c33632104fd399ac94a00332a1ff','3a16c33632104fd399ac94a00332a1ff',0,'56E76568A1A245E38F2D0649CBD56C95')";
            //执行SQL语句
            db.execSQL(stu_sql);
            num++;
        }
        return num;
    }

}
